package recursion;

public class EightQueens {
    // 定义一个数组，保存皇后的位置
    //下标表示皇后放置的行，值表示放置的列
    int max = 8;
    int[] chess = new int[max];
    int total = 0 ;

    public static void main(String[] args) {
        EightQueens eightQueens = new EightQueens();
        eightQueens.put(0);
        System.out.println("total = " + eightQueens.total);


    }

    // 放置皇后
    public void put(int n) {
        if (n == max) {
            //说明已经放好了
            print();
            total++;
            return;
        }
        for (int i = 0; i < max; i++){
            chess[n]  = i;
            if(judge(n)){
                put(n + 1);
            }
        }

    }

    //判断本次放置的皇后是否和之前的皇后冲突
    //n表示的是下标 即第n+1个皇后
    public boolean judge(int n) {
        for (int i = 0; i < n; i++) {
            if (chess[i] == chess[n] || Math.abs(chess[i] - chess[n]) == Math.abs(n - i)) {
                //说明皇后放置冲突
                return false;
            }
        }
        return true;
    }

    //打印出八皇后的解法
    public void print() {
        for (int i = 0; i < 8; i++) {
            System.out.print(chess[i] + " ");
        }
        System.out.println();
    }
}
